import {Component} from '@angular/core';
import {FormArray, FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {StudyShareModule} from "../../StudyShareModule";
import {JsonPipe} from "@angular/common";
import {Person} from "../../../services/common/User ";

@Component({
  selector: 'app-comment-add',
  standalone: true,
  imports: [StudyShareModule,JsonPipe],
  templateUrl: './comment-add.component.html',
  styleUrls: []
})
export class CommentAddComponent {
  name = new FormControl('1'); // 默认值为''

  person = new Person('', '', '建设路32号', '成都市');

  // 构建表单 方式2
  userInfo = this.fb.group({
    firstName: ['',[Validators.required,Validators.minLength(4)]],
    lastName: ['232',[Validators.required,Validators.minLength(6)]],
    age: [1,[Validators.required,Validators.min(1),Validators.max(100)]],
    address: this.fb.group({
      street: ['建设路32号'],
      city: ['成都市']
    }),
    sizes: this.fb.array([
      this.fb.control('')
    ])
  });
  //构建表单数据 方式1
 /* userInfo = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    address: new FormGroup({ // 新增，并设置默认值
      street: new FormControl('建设路32号'),
      city: new FormControl('成都市')
    })
  });*/

  constructor(private fb: FormBuilder) {
  }

  onSubmit() {
    console.log(this.userInfo.value);
  }

  onSubmit2() {
    console.log(this.person);
  }
  onSubmit3(o:any) {
    console.log(o.form.value);
    console.log(JSON.stringify(o.form.value));
  }

  onSetValue(): void {
    this.userInfo.setValue({
      firstName: '12312',
      lastName: '123',
      age: 1,
      address: {
        city: '北京市',
        street: 'da',
      },
      sizes: []
    });
  }
  onPatchValue(): void {
    //这里值修改自定字段
    this.userInfo.patchValue({
      address: {
        city: '北京市'
      }
    });
  }

  get sizes() {
    return this.userInfo.get('sizes') as FormArray; // 断言为FormArray类型
  }

  addSize(): void {
    this.sizes.push(this.fb.control(''));
  }
  deleteSize(): void {
    this.sizes.removeAt(0);
  }

  // 因为我们可能多次获取表单中元素，所以先获取
  get firstName() { return this.userInfo.get('firstName'); }
  get lastName() { return this.userInfo.get('lastName'); }
  get age(){return this.userInfo.get('age')}
  get address(){return this.userInfo.get('address')}
}
